package com.kunyi.web.service.file.core.handel.Impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.kunyi.web.service.file.core.enums.KunyiRepositoryTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

/**
 * @ClassName KunyiOSSRepository
 * @Description oss操作具体实现
 * @Author zhenguo.zhuang
 * @Date 2024/3/13 9:34
 * @Version 1.0
 */
@Slf4j
@Scope("prototype")
@Component("ossRepository")
public class KunyiOssRepository extends KunyiRepositoryAbstract  {
    /**
     *连接对象
     */
    private OSSClient OSS;

    @Override
    void loginInSpecific(String accessKeyId, String accessKeySecret, String endPoint){
        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        ossClient.getBucketLocation(bucketName);
        OSS = ossClient;
    }

    @Override
    boolean isFileExistSpecific(String filePath) throws RuntimeException {
        if (OSS.doesObjectExist(bucketName, filePath)) {
            return true;
        }
        return false;
    }

    @Override
    boolean createDirSpecific(String filePath) throws RuntimeException {
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(0);
        meta.setContentEncoding("UTF-8");
        OSS.putObject(this.bucketName,filePath,new ByteArrayInputStream(new byte[0]),meta);
        return true;
    }

    @Override
    void uploadSpecific(String filePath,String fileName,String appendFilePath, InputStream inputStream , Long length,MultipartFile multipartFile,File file) throws RuntimeException {
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentEncoding("UTF-8");
        AppendObjectRequest request = new AppendObjectRequest(bucketName,appendFilePath,inputStream,meta);
        request.setPosition(0L);
        OSS.appendObject(request);
    }


    @Override
    boolean deleteFileSpecific(String filePath) throws RuntimeException{
        OSS.deleteObject(bucketName,filePath);
        return true;
    }

    @Override
    InputStream readStreamsSpecific(String filePath) throws RuntimeException{
        OSSObject object = OSS.getObject(bucketName, filePath);
        InputStream in = object.getObjectContent();
        return in;
    }

    @Override
    KunyiRepositoryTypeEnum type() {
        return KunyiRepositoryTypeEnum.OSS;
    }



}
